<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <div class="math-icon">📊</div>
        <h1>欢迎回来</h1>
        <p>继续你的数学学习之旅</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="formData"
        :rules="rules"
        @submit.prevent="handleLogin"
        class="login-form"
        label-position="top"
        size="default"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <div class="form-options">
          <el-checkbox v-model="formData.remember">记住我</el-checkbox>
          <el-link type="primary" :underline="false">忘记密码？</el-link>
        </div>

        <el-form-item>
          <el-button type="primary" class="login-btn" :loading="isLoading" @click="handleLogin">
            {{ isLoading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <p>还没有账号？</p>
        <router-link to="/register" class="register-link">立即注册</router-link>
      </div>

      <div class="math-decoration">
        <div class="math-symbol">∑</div>
        <div class="math-symbol">π</div>
        <div class="math-symbol">∞</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const loginFormRef = ref<FormInstance>()
const authStore = useAuthStore()

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  remember: false,
})

// 表单状态
const isLoading = computed(() => authStore.isLoading)

// 表单验证规则
const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    {
      validator: (_rule, value: string, callback) => {
        if (!value) return callback(new Error('请输入用户名'))
        const re = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/
        if (!re.test(value)) return callback(new Error('用户名只能包含字母、数字、下划线和中文'))
        callback()
      },
      trigger: ['blur', 'change'],
    },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    {
      validator: (_rule, value: string, callback) => {
        if (!value) return callback(new Error('请输入密码'))
        const hasLetter = /[a-zA-Z]/.test(value)
        const hasNumber = /\d/.test(value)
        if (!hasLetter || !hasNumber) return callback(new Error('密码必须包含字母和数字'))
        callback()
      },
      trigger: ['blur', 'change'],
    },
  ],
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()

    // 使用认证store进行登录
    const success = await authStore.login({
      username: formData.username,
      password: formData.password,
    })
    console.log(success, 'success--登录')
    if (success) {
      ElMessage.success('登录成功！')
      // 登录成功后跳转到首页
      router.push('/')
    } else {
      // 错误信息已经在store中处理
      ElMessage.error(authStore.error || '登录失败，请检查用户名和密码')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请检查用户名和密码')
  }
}

// 监听错误状态变化
watch(
  () => authStore.error,
  (newError) => {
    if (newError) {
      ElMessage.error(newError)
      authStore.clearError()
    }
  },
)
</script>

<style lang="less" scoped>
// 变量定义
@primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
@text-primary: #333;
@text-secondary: #666;
@white: #fff;
@shadow: 0 16px 32px rgba(0, 0, 0, 0.1);
@border-radius: 16px;
@transition: all 0.3s ease;

.login-container {
  height: calc(100vh - 126px);
  min-height: 100%; // 改为100%避免与外层导航叠加
  display: flex;
  align-items: center;
  justify-content: center;
  background: @primary-gradient;
  padding: 16px;

  .login-card {
    background: @white;
    border-radius: @border-radius;
    padding: 24px;
    width: 100%;
    max-width: 380px;
    box-shadow: @shadow;
    position: relative;
    overflow: hidden;

    .login-header {
      text-align: center;
      margin-bottom: 20px;

      .math-icon {
        font-size: 2.4rem;
        margin-bottom: 10px;
      }

      h1 {
        color: @text-primary;
        font-size: 1.5rem;
        margin-bottom: 6px;
        font-weight: 600;
      }

      p {
        color: @text-secondary;
        font-size: 0.92rem;
      }
    }

    .login-form {
      margin-bottom: 16px;

      // Element Plus 表单样式优化（顶置标签）
      :deep(.el-form-item) {
        margin-bottom: 16px;
      }

      :deep(.el-form-item__label) {
        padding-bottom: 6px;
        font-size: 0.9rem;
        font-weight: 500;
        display: block;
      }

      :deep(.el-input__wrapper) {
        border-radius: 8px;
        padding-inline: 10px;
      }
    }

    .form-options {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 14px;
    }

    .login-btn {
      width: 100%;
      height: 40px;
      background: @primary-gradient;
      border: none;
      border-radius: 8px;
      font-weight: 600;
      transition: @transition;

      &:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
      }
    }

    .login-footer {
      text-align: center;
      margin-top: 20px;

      p {
        color: @text-secondary;
        margin-bottom: 6px;
        font-size: 0.9rem;
      }

      .register-link {
        color: #667eea;
        text-decoration: none;
        font-weight: 600;
        transition: @transition;

        &:hover {
          color: #5a6fd8;
        }
      }
    }

    .math-decoration {
      position: absolute;
      top: 0;
      right: 0;
      width: 72px;
      height: 72px;
      opacity: 0.06;
      pointer-events: none;

      .math-symbol {
        position: absolute;
        font-size: 1.4rem;
        color: #667eea;

        &:nth-child(1) {
          top: 12px;
          right: 12px;
        }

        &:nth-child(2) {
          top: 36px;
          right: 36px;
        }

        &:nth-child(3) {
          top: 60px;
          right: 12px;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 480px) {
  .login-container {
    .login-card {
      padding: 20px 16px;
      margin: 12px;

      .login-header h1 {
        font-size: 1.35rem;
      }

      .form-options {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
      }
    }
  }
}
</style>
